package com.zx.dsptuneup_TriMic.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.base.tools.tools.AppUtils;
import com.example.base.tools.tools.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.multilevel.treelist.Node;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.zx.dsptuneup_TriMic.Adapter.EquipListAdapter;
import com.zx.dsptuneup_TriMic.Base.BaseActivity;
import com.zx.dsptuneup_TriMic.Common.TextDrawable;
import com.zx.dsptuneup_TriMic.NodeTree.MTreeRecycleAdapter;
import com.zx.dsptuneup_TriMic.R;
import com.zx.dsptuneup_TriMic.Tools.CVIPaperDialogUtils;
import com.zx.dsptuneup_TriMic.Tools.Constant;
import com.zx.dsptuneup_TriMic.Tools.PermissionManager;
import com.zx.dsptuneup_TriMic.Tools.UrlConstant;
import com.zx.dsptuneup_TriMic.Util.ClickUtil;
import com.zx.dsptuneup_TriMic.Util.Constants;
import com.zx.dsptuneup_TriMic.Util.MultiControlDialogUtil;
import com.zx.dsptuneup_TriMic.Util.NetWorkUtils;
import com.zx.dsptuneup_TriMic.Util.ToastUtil;
import com.zx.dsptuneup_TriMic.Util.UserUtil;
import com.zx.dsptuneup_TriMic.bean.BasicResponse;
import com.zx.dsptuneup_TriMic.bean.ChildDeviceBean;
import com.zx.dsptuneup_TriMic.bean.DeviceBean;
import com.zx.dsptuneup_TriMic.bean.ScanDevBean;
import com.zx.dsptuneup_TriMic.bean.TreeListBean;
import com.zx.dsptuneup_TriMic.fragment.InputFragment;
import com.zx.dsptuneup_TriMic.fragment.InputGainFragment;
import com.zx.dsptuneup_TriMic.network.AddTokenInterceptor;
import com.zx.dsptuneup_TriMic.network.DefaultObserver;
import com.zx.dsptuneup_TriMic.network.NetWorkManager;
import com.zx.dsptuneup_TriMic.widget.ui.ClearEditText;
import com.zx.dsptuneup_TriMic.widget.ui.CustomOperateDialog;
import com.zx.dsptuneup_TriMic.widget.ui.DividerItemDecoration;
import com.zx.dsptuneup_TriMic.widget.ui.EmptyView;
import com.zx.dsptuneup_TriMic.widget.ui.LoadingView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 *  首页设备列表
 * */
public class HomeListActivity extends BaseActivity implements MTreeRecycleAdapter.treeOperationInterface,MTreeRecycleAdapter.OnItemClickListener,EquipListAdapter.OnDevicesOperationListener, EasyPermissions.PermissionCallbacks{
    @BindView(R.id.ic_nav)
    TextView nav_left;
    @BindView(R.id.listView)
    ExpandableListView listView;
    @BindView(R.id.inc_empty_view)
    EmptyView mIEmptyView;
    @BindView(R.id.inc_loading_view)
    LoadingView mILoadingView;
    @BindView(R.id.scan)
    ImageView scan;
    @BindView(R.id.addNewDevTxt)
    TextView addNewDevTxt;
    @BindView(R.id.iv_setting)
    TextView iv_setting;
    @BindView(R.id.control_rl)
    RelativeLayout control_rl;
    @BindView(R.id.left_control)
    TextView left_control;
    @BindView(R.id.right_control)
    TextView right_control;
    @BindView(R.id.multi_sel_title)
    TextView multi_sel_title;      //多选控制标题
    @BindView(R.id.multi_sel_cancel)
    TextView multi_sel_cancel;      //多选取消
    @BindView(R.id.multi_sel_selAll)
    TextDrawable multi_sel_selAll;  //多选全选
    @BindView(R.id.search_edittext)
    ClearEditText search_edittext;  // 搜索按钮
    @BindView(R.id.exit)
    ImageView exit;                  // 退出按钮
    @BindView(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;     // 下拉刷新


    private boolean isManager = false;
    private PopupWindow mPop = null;
    private Drawable drawable_selected = null;
    private Drawable drawable_normal = null;
    private CustomOperateDialog mBubbleDialog = null;

    private MTreeRecycleAdapter mAdapter;
    private EquipListAdapter equipListAdapter;
    protected List<Node> mDatas = new ArrayList<Node>();            // 树状图数据结构\
    private String currentSelPositionId = "";   // 当前选择的位置信息
    protected List<DeviceBean> deviceList = new ArrayList<>();   // 设备列表
    private List<List<ChildDeviceBean>>  childs = new ArrayList<>(10);   // 子设备列表，后面初始化容量
    private int returenChildSize = 0;

    private int REQUEST_CODE = 10086;
    /**点击返回时间*/
    private long time = 2000;
    private long first_time = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_list);
        initUI();
        mILoadingView.showLoading();
        checkWritePermission1();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initUI() {
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initData();
            }
        });

        Rect bonds = new Rect(0, 0, 17,9);
        Rect bond_r = new Rect(0, 0, 8,14);
        drawable_selected = getResources().getDrawable(R.mipmap.arrow);
        drawable_selected.setBounds(bonds);

        drawable_normal = getResources().getDrawable(R.mipmap.arrow_r);
        drawable_normal.setBounds(bond_r);

        nav_left.setSelected(false);
        nav_left.setCompoundDrawables(null, null, drawable_normal, null);
        nav_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nav_left.setSelected(!nav_left.isSelected());
                if(nav_left.isSelected()){
                    nav_left.setCompoundDrawables(null, null, drawable_selected, null);
                }else{
                    nav_left.setCompoundDrawables(null, null, drawable_normal, null);
                }
                if (mPop != null && mPop.isShowing()) {
                    mPop.dismiss();
                }else {
                    showPopupWindow(view);
                }
            }
        });
        search_edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    String searchTxt = search_edittext.getText().toString();
                   if(StringUtils.isEmpty(searchTxt)){
                       ToastUtil.makeText(HomeListActivity.this,"请输入搜索信息!");
                       return false;
                   }else {
                       HashMap map = new HashMap();
                       map.put("positionId",currentSelPositionId);
                       map.put("deviceName",searchTxt);

                       requestDevicesListData(map);
                   }
                }
                return false;
            }
        });
        // 退出登录按钮逻辑
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 删除
                CVIPaperDialogUtils.showCustomDialog(HomeListActivity.this, "确定要退出登录吗?", null, "退出", false, new CVIPaperDialogUtils.ConfirmDialogListener() {
                    @Override
                    public void onClickButton(boolean clickConfirm, boolean clickCancel) {
                        if (clickConfirm) {
                            HashMap map = new HashMap();
                            if(Hawk.contains(Constant.username)){
                                map.put("username",Hawk.get(Constant.username));
                            }

                            NetWorkManager.getInstance().getNetWorkApiService().loginOutByUserName(map).compose(HomeListActivity.this.<BasicResponse<String>>bindToLifecycle())
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                        @Override
                                        protected void onSuccess(BasicResponse<String> response) {
                                            if (response != null) {
                                                Intent intent = new Intent(HomeListActivity.this, LoginActivity.class);
                                                startActivity(intent);
                                                finish();

                                            }
                                        }
                                        @Override
                                        protected void onFail(BasicResponse<String> response) {
                                            super.onFail(response);

                                        }
                                        @Override
                                        public void onError(@NonNull Throwable e) {
                                            super.onError(e);
                                        }
                                    });

                        }
                    }
                });

            }
        });

        search_edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(StringUtils.isEmpty(editable.toString()) ){
                    String positionId = currentSelPositionId;
                    HashMap map = new HashMap();
                    map.put("positionId",positionId);
                    currentSelPositionId = positionId;

                    requestDevicesListData(map);
                }
            }
        });

        // 录入新设备
        addNewDevTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent intent6 = new Intent(HomeListActivity.this, ReplaceActivity.class);
//                startActivity(intent6);

                if (ClickUtil.isFastClick(1000, view)) {
                    return;
                }
                String positionId = currentSelPositionId;
                if(StringUtils.isEmpty(positionId)){
                    ToastUtil.makeText(HomeListActivity.this,"未选择当前位置信息!");
                    return;
                }
//                ChooseDevicesDialogUtil.showAlertDialog(HomeListActivity.this, false, new ChooseDevicesDialogUtil.ConfirmDialogListener() {
//                    @Override
//                    public void onClickButton(boolean clickParent, boolean clickChild) {
//                        boolean isParent = clickParent;
//
//                    }
//                });

                Intent intent = new Intent(HomeListActivity.this, AddNewDevActivity.class);
                intent.putExtra(Constant.addDevicesType, true);      // type
                intent.putExtra(Constant.addDevicesPositionID,positionId);// 位置信息
                startActivity(intent);
            }
        });

        // 扫一扫
        scan.setVisibility(View.GONE);
        scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(HomeListActivity.this, CaptureActivity.class);
                startActivityForResult(intent,REQUEST_CODE);
            }
        });

        //  批量控制
        iv_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (deviceList.size()<=0){
                    ToastUtil.makeText(HomeListActivity.this,"暂无设备可以控制!");
                    return;
                }
                // list动态改变高度 减去下面的controllView的高度
                ViewGroup.LayoutParams params = listView.getLayoutParams();
                int totalHeight = listView.getHeight() - AppUtils.dip2px(HomeListActivity.this,52);
                params.height = totalHeight;
                listView.setLayoutParams(params);

                // 出现取消和全选按钮
                iv_setting.setVisibility(View.GONE);
                nav_left.setVisibility(View.GONE);
                addNewDevTxt.setVisibility(View.GONE);
                scan.setVisibility(View.GONE);

                multi_sel_title.setVisibility(View.VISIBLE);
                multi_sel_cancel.setVisibility(View.VISIBLE);
                multi_sel_selAll.setVisibility(View.VISIBLE);

                setBottomControllView(); 
            }
        });
        // 批量 取消
        multi_sel_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetMormalUI();
            }
        });

        // 批量 全选
        multi_sel_selAll.setSelected(false);
        multi_sel_selAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                multi_sel_selAll.setSelected(!multi_sel_selAll.isSelected());
                if(multi_sel_selAll.isSelected()){
                    equipListAdapter.sellectAll();
                }else{
                    equipListAdapter.cancelSelectAll();
                }
            }
        });

        //批量控制
        left_control.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<DeviceBean> SelectedDevList =  equipListAdapter.getSelectedItem();
                if(SelectedDevList.size()<=0){
                    ToastUtil.makeText(HomeListActivity.this,"请先选择一个设备!");
                    return;
                }
                MultiControlDialogUtil.showAlertDialog(HomeListActivity.this, false, new MultiControlDialogUtil.ConfirmDialogListener() {
                    @Override
                    public void onClickButton(String elememtType,int channel,MultiControlDialogUtil.MultiControlType type, boolean isRemote, boolean isMute, float volume, boolean clickReset, boolean clickRestart) {
                        String groups = "";
                        String ids    = "";
                        for (int i=0;i<SelectedDevList.size();i++){
                            DeviceBean deviceBean = SelectedDevList.get(i);
                            if(i<SelectedDevList.size()-1){
                                groups += deviceBean.getGroup() + ",";
                                ids += deviceBean.getId() + ",";
                            }else {
                                groups += deviceBean.getGroup();
                                ids += deviceBean.getId() ;
                            }
                        }
                        HashMap map = new HashMap();
                        map.put("groups", groups);
                        map.put("type", elememtType);
                        map.put("channel",channel);
                        switch (type) {
                            case CONTROL_MUTE:
                                map.put("mute",isMute ? 1:0);
                                NetWorkManager.getInstance().getNetWorkApiService().setMute(map).compose(HomeListActivity.this.<BasicResponse<String>>bindToLifecycle())
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                            @Override
                                            protected void onSuccess(BasicResponse<String> response) {
                                                if (response != null) {
                                                    ToastUtil.makeText(HomeListActivity.this,"设置成功!");
                                                }
                                            }
                                            @Override
                                            protected void onFail(BasicResponse<String> response) {
                                                super.onFail(response);

                                            }
                                            @Override
                                            public void onError(@NonNull Throwable e) {
                                                super.onError(e);
                                            }
                                        });
//                                ToastUtil.makeText(HomeListActivity.this,elememtType + "---" +channel+ "--点击静音=="+isMute);
                                break;
                            case CONTROL_REMOTE:
                                map.remove("type");
                                map.remove("channel");
                                map.put("mode",isRemote ? 1:0);
                                NetWorkManager.getInstance().getNetWorkApiService().setRemote(map).compose(HomeListActivity.this.<BasicResponse<String>>bindToLifecycle())
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                            @Override
                                            protected void onSuccess(BasicResponse<String> response) {
                                                if (response != null) {
                                                    ToastUtil.makeText(HomeListActivity.this,"设置成功!");
                                                }
                                            }
                                            @Override
                                            protected void onFail(BasicResponse<String> response) {
                                                super.onFail(response);
                                            }
                                            @Override
                                            public void onError(@NonNull Throwable e) {
                                                super.onError(e);
                                            }
                                        });
//                                ToastUtil.makeText(HomeListActivity.this,elememtType + "---" +channel+ "点击了远程=="+isRemote);
                                break;
                            case CONTROL_VOLUME:
                                map.put("volume",(int)volume);
                                NetWorkManager.getInstance().getNetWorkApiService().setVolume(map).compose(HomeListActivity.this.<BasicResponse<String>>bindToLifecycle())
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                            @Override
                                            protected void onSuccess(BasicResponse<String> response) {
                                                if (response != null) {
                                                    ToastUtil.makeText(HomeListActivity.this,"设置成功!");
                                                }
                                            }
                                            @Override
                                            protected void onFail(BasicResponse<String> response) {
                                                super.onFail(response);

                                            }
                                            @Override
                                            public void onError(@NonNull Throwable e) {
                                                super.onError(e);
                                            }
                                        });
//                                ToastUtil.makeText(HomeListActivity.this,elememtType + "---" +channel+ "点击音量==当前音量"+volume);
                                break;
                            case CONTROL_RESET:
                                NetWorkManager.getInstance().getNetWorkApiService().resetDevice(ids).compose(HomeListActivity.this.<BasicResponse<String>>bindToLifecycle())
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                            @Override
                                            protected void onSuccess(BasicResponse<String> response) {
                                                if (response != null) {
                                                    ToastUtil.makeText(HomeListActivity.this,"设置成功!");
                                                }
                                            }
                                            @Override
                                            protected void onFail(BasicResponse<String> response) {
                                                super.onFail(response);
                                            }
                                            @Override
                                            public void onError(@NonNull Throwable e) {
                                                super.onError(e);
                                            }
                                        });

//                                ToastUtil.makeText(HomeListActivity.this,elememtType + "---" +channel+ "点击恢复出厂设置=="+clickReset);
                                break;
                            case CONTROL_RESTART:
                                NetWorkManager.getInstance().getNetWorkApiService().restartDevice(ids).compose(HomeListActivity.this.<BasicResponse<String>>bindToLifecycle())
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                            @Override
                                            protected void onSuccess(BasicResponse<String> response) {
                                                if (response != null) {
                                                    ToastUtil.makeText(HomeListActivity.this,"设置成功!");
                                                }
                                            }
                                            @Override
                                            protected void onFail(BasicResponse<String> response) {
                                                super.onFail(response);
                                            }
                                            @Override
                                            public void onError(@NonNull Throwable e) {
                                                super.onError(e);
                                            }
                                        });
//                                ToastUtil.makeText(HomeListActivity.this,elememtType + "---" +channel+ "点击重启=="+clickRestart);
                                break;
                        }
                    }
                });
            }
        });

        /**
         * 批量删除
         * */
        right_control.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               List<DeviceBean> deviceBeanList =  equipListAdapter.getSelectedItem();
               if(deviceBeanList.size()<=0){
                   ToastUtil.makeText(HomeListActivity.this,"请先选择一个设备!");
                   return;
               }
                // 删除
                CVIPaperDialogUtils.showCustomDialog(HomeListActivity.this, "确定要批量删除吗?", null, "删除", false, new CVIPaperDialogUtils.ConfirmDialogListener() {
                    @Override
                    public void onClickButton(boolean clickConfirm, boolean clickCancel) {
                        if (clickConfirm) {
                            List<DeviceBean> SelectedList = equipListAdapter.getSelectedItem();

                            String ids = "";
                            for (int i=0;i<SelectedList.size();i++){
                                DeviceBean deviceBean = SelectedList.get(i);
                                if(i<SelectedList.size()-1){
                                    ids += deviceBean.getId() + ",";
                                }else {
                                    ids += deviceBean.getId();
                                }
                            }

                            NetWorkManager.getInstance().getNetWorkApiService().delList(ids).compose(HomeListActivity.this.<BasicResponse<String>>bindToLifecycle())
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                        @Override
                                        protected void onSuccess(BasicResponse<String> response) {
                                            if (response != null) {
                                                for (DeviceBean deviceBean: SelectedList){
                                                    deviceList.remove(deviceBean);
                                                }
                                                equipListAdapter.setGridViewBeanList(deviceList);
                                                equipListAdapter.notifyDataSetChanged();
                                                //  全选模式转回正常显示的模式
                                                resetMormalUI();
                                                judgeEmptyViewShow();
                                            }
                                        }
                                        @Override
                                        protected void onFail(BasicResponse<String> response) {
                                            super.onFail(response);

                                        }
                                        @Override
                                        public void onError(@NonNull Throwable e) {
                                            super.onError(e);
                                        }
                                    });

                        }
                    }
                });

            }
        });

        equipListAdapter = new EquipListAdapter(this, deviceList,childs);
        equipListAdapter.setGridViewBeanList(deviceList);
        equipListAdapter.setOnDevicesOperationListener(HomeListActivity.this);

        listView.setAdapter(equipListAdapter);
//        listView.expandGroup(0);
        mIEmptyView = (EmptyView)findViewById(R.id.inc_empty_view);
        mIEmptyView.setEmptyTip("暂无数据");
//        listView.setEmptyView(mIEmptyView);
        mIEmptyView.setVisibility(View.GONE);
        listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition, long l) {
                // 正在进行多选控制，此时不用展开
                equipListAdapter.groupItemClick(groupPosition);
                if (isManager){
                    return true;
                }else {
                    // 请求子设备列表
                    int size = requestChildDevList(deviceList.get(groupPosition).getGroup()+"",groupPosition);
                    Log.e("hahahaha","size=="+size);
                    if(size>0){
                        equipListAdapter.setChilds(childs);
                    }
                    return size>0 ? false :true;
                }
            }
        });

    }

    /**
     * 请求设备列表数据
     * */
    private void requestDevicesListData(HashMap map) {
        NetWorkManager.getInstance().getNetWorkApiService().getDevList(map).compose(HomeListActivity.this.<BasicResponse<List<DeviceBean>>>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<BasicResponse<List<DeviceBean>>>() {
                    @Override
                    protected void onSuccess(BasicResponse<List<DeviceBean>> response) {
                        mILoadingView.hideLoading();
                        if (response != null) {
                            mRefreshLayout.finishRefresh();
                            deviceList = response.getData();

                            // 对child占位
                            childs.clear();
                            for (int i=0;i<deviceList.size();i++){
                                List<ChildDeviceBean> list = new ArrayList<>();
                                childs.add(list);
                            }
                            equipListAdapter.setGridViewBeanList(deviceList);

                            mILoadingView.hideLoading();
                            judgeEmptyViewShow();
                        }
                    }

                    @Override
                    protected void onFail(BasicResponse<List<DeviceBean>> response) {
                        super.onFail(response);
                        mRefreshLayout.finishRefresh();
                        mILoadingView.hideLoading();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        super.onError(e);
                        mRefreshLayout.finishRefresh();
                        mILoadingView.hideLoading();
                    }
                });
    }

    /**
     * 批量选择模式切换回正常模式
     * */
    private void resetMormalUI(){
        // list动态改变高度
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        int totalHeight = listView.getHeight() + AppUtils.dip2px(HomeListActivity.this,52);
        params.height = totalHeight;
        listView.setLayoutParams(params);

        // 隐藏取消和全选按钮
        iv_setting.setVisibility(View.VISIBLE);
        nav_left.setVisibility(View.VISIBLE);
        addNewDevTxt.setVisibility(View.VISIBLE);
//        scan.setVisibility(View.VISIBLE);
        multi_sel_title.setVisibility(View.GONE);
        multi_sel_cancel.setVisibility(View.GONE);
        multi_sel_selAll.setVisibility(View.GONE);

        setBottomControllView();
    }
    /**
     * 气泡弹框点击
     */
    @Override
    public void onItemClicked(boolean isParent, int bubblePosition,int groupIndex,int childPosition,String groupId) {
        if(isParent){
            DeviceBean deviceBean = deviceList.get(groupIndex);
            String ids = deviceBean.getId();
           switch (bubblePosition){
               case 0:
                   if(deviceBean.getStatus() > 2){
                       ToastUtil.makeText(HomeListActivity.this,"设备掉线不可控制!");
                       return;
                   }
                   // 控制
                   Intent intent1 = new Intent(HomeListActivity.this, HomeActivity.class);
                   intent1.putExtra(Constant.addDevicesID, ids);
                   intent1.putExtra(Constant.GroupID, deviceBean.getGroup());
                   startActivity(intent1);
                   break;
               case 1:
                   CVIPaperDialogUtils.showCustomDialog(HomeListActivity.this, "确定要删除该主设备吗?", null, "删除", false, new CVIPaperDialogUtils.ConfirmDialogListener() {
                       @Override
                       public void onClickButton(boolean clickConfirm, boolean clickCancel) {
                           if(clickConfirm){
                               DeviceBean deviceBean = deviceList.get(groupIndex);
                               String ids = deviceBean.getId();

                               //删除
                               NetWorkManager.getInstance().getNetWorkApiService().delList(ids).compose(HomeListActivity.this.<BasicResponse<String>>bindToLifecycle())
                                       .subscribeOn(Schedulers.io())
                                       .observeOn(AndroidSchedulers.mainThread())
                                       .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                           @Override
                                           protected void onSuccess(BasicResponse<String> response) {
                                               if (response != null) {
                                                   deviceList.remove(groupIndex);
                                                   equipListAdapter.setGridViewBeanList(deviceList);
                                                   equipListAdapter.notifyDataSetChanged();
                                                   judgeEmptyViewShow();
                                               }
                                           }
                                           @Override
                                           protected void onFail(BasicResponse<String> response) {
                                               super.onFail(response);

                                           }
                                           @Override
                                           public void onError(@NonNull Throwable e) {
                                               super.onError(e);
                                           }
                                       });
                           }
                       }
                   });
                   break;
               case 2:
                   CVIPaperDialogUtils.showInputDialog(HomeListActivity.this, "请输入修改后的设备名称", "确定","10字以内", InputType.TYPE_CLASS_TEXT, false, new CVIPaperDialogUtils.inputConfirmDialogListener() {
                       @Override
                       public void onClickButton(boolean clickConfirm, boolean clickCancel, String inputStr) {
                           if (clickConfirm) {
                               if (StringUtils.isEmpty(inputStr)) {
                                   ToastUtil.makeText(HomeListActivity.this, "请输入名称!");
                               } else {
                                   DeviceBean deviceBean = deviceList.get(groupIndex);
                                   String ids = deviceBean.getId();

                                   HashMap map = new HashMap();
                                   map.put("positionId", currentSelPositionId);
                                   map.put("deviceName", inputStr);
                                   map.put("id", ids);
//
                                   NetWorkManager.getInstance().getNetWorkApiService().deviceMod(map).compose(HomeListActivity.this.<BasicResponse<String>>bindToLifecycle())
                                           .subscribeOn(Schedulers.io())
                                           .observeOn(AndroidSchedulers.mainThread())
                                           .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                               @Override
                                               protected void onSuccess(BasicResponse<String> response) {
                                                   if (response != null) {
                                                       refreshPositionTreeData();
                                                       if (mBubbleDialog != null && mBubbleDialog.isShowing()) {
                                                           mBubbleDialog.dismiss();
                                                       }
                                                       ToastUtil.makeText(HomeListActivity.this, "修改成功!");
                                                   }
                                               }

                                               @Override
                                               protected void onFail(BasicResponse<String> response) {
                                                   super.onFail(response);

                                               }

                                               @Override
                                               public void onError(@NonNull Throwable e) {
                                                   super.onError(e);
                                               }
                                           });
                               }
                           }
                       }
                   });
                   break;
               case 3:
                   Intent intent = new Intent(HomeListActivity.this, AddNewDevActivity.class);
                   intent.putExtra(Constant.addDevicesType, false);      // type
                   intent.putExtra(Constant.addDevicesID,groupId);// 位置信息
                   startActivity(intent);
                   break;
               case 4:
                   Intent intent4 = new Intent(HomeListActivity.this, TransferParentActivity.class);
                   intent4.putExtra(Constant.addDevicesID, ids);
                   startActivity(intent4);

                   break;
               case 5:
                   Intent intent5 = new Intent(HomeListActivity.this, ReplaceActivity.class);
                   intent5.putExtra(Constant.addDevicesID, ids);
                   intent5.putExtra(Constant.addDevicesType, true);
                   startActivity(intent5);
                   break;
           }
        }else {
            String childId = childs.get(groupIndex).get(childPosition).getId();
            switch (bubblePosition){
                case 0:
                    break;
                case 1:
                    CVIPaperDialogUtils.showCustomDialog(HomeListActivity.this, "确定要删除该子设备吗?", null, "删除", false, new CVIPaperDialogUtils.ConfirmDialogListener() {
                        @Override
                        public void onClickButton(boolean clickConfirm, boolean clickCancel) {
                            if(clickConfirm){
                                // 删除子设备

                                NetWorkManager.getInstance().getNetWorkApiService().deleteChildDevice(childId).compose(HomeListActivity.this.<BasicResponse<String>>bindToLifecycle())
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                            @Override
                                            protected void onSuccess(BasicResponse<String> response) {
                                                if (response != null) {
                                                    childs.get(groupIndex).remove(childPosition);

                                                    // child对应groupIndex子目录删完，删除该groupIndex 的list
//                                                    if(childs.get(groupIndex).size()==0){
//                                                        childs.remove(groupIndex);
//                                                    }

                                                    if(childs.size()>0){
                                                        if( childs.get(groupIndex).size()>0){
                                                            equipListAdapter.setChilds(childs);
                                                        }else {
                                                            listView.collapseGroup(groupIndex);
                                                        }
                                                    }else {
                                                        listView.collapseGroup(groupIndex);
                                                    }
                                                }
                                            }
                                            @Override
                                            protected void onFail(BasicResponse<String> response) {
                                                super.onFail(response);
                                            }
                                            @Override
                                            public void onError(@NonNull Throwable e) {
                                                super.onError(e);
                                            }
                                        });
                            }
                        }
                    });

                    break;
                case 2:
                    break;
                case 3:

                    break;
                case 4:
                    Intent intent4 = new Intent(HomeListActivity.this, TransferChildActivity.class);
                    intent4.putExtra(Constant.addDevicesID, childId);
                    startActivity(intent4);

                    break;
                case 5:
                    Intent intent5 = new Intent(HomeListActivity.this, ReplaceActivity.class);
                    intent5.putExtra(Constant.addDevicesID, childId);
                    intent5.putExtra(Constant.addDevicesType, false);
                    startActivity(intent5);
                    break;
            }
        }
    }

    /**
     * 请求子设备列表，返回子设备个数，用于判断展开状态，同步回调
     */
    private int requestChildDevList(String groupId,int groupPosition) {
        returenChildSize = 0; // 每次置0
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient.Builder().readTimeout(2, TimeUnit.SECONDS).addInterceptor(new AddTokenInterceptor()).build();
                Request request = new Request.Builder().url(UrlConstant.baseUrl+"/device/getChildByGroup?group="+groupId)
                        .get().build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    BasicResponse<List<ChildDeviceBean>> data = new Gson().fromJson(response.body().string(),new TypeToken<BasicResponse<List<ChildDeviceBean>>>() {}.getType());
                    if(data.getData() != null && data.getData().size()>0){
                        returenChildSize =data.getData().size();
                        childs.remove(groupPosition);
                        childs.add(groupPosition, data.getData());
//                                    listView.collapseGroup()
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();

        try {
            thread.join();
        }catch (InterruptedException e) {
            e.printStackTrace();

        }
        return returenChildSize;
    }

    /**
     *  加载树形数据和设备列表
     * */
    private void initTreeDatas(List<TreeListBean> originalData) {
        if(originalData.size()<1){
            mRefreshLayout.finishRefresh();
            mILoadingView.hideLoading();
            judgeEmptyViewShow();
            return;
        }

        mDatas.clear();
        if(originalData.size()==1){
            Node node = new Node(originalData.get(0).getId(),-1,originalData.get(0).getPositionName());
            mDatas.add(node);
        }else {
            for (int i=0;i<originalData.size();i++){
                TreeListBean treeListBean = originalData.get(i);
                Node node;
                if(StringUtils.isEmpty(treeListBean.getParentId()) ){
                     node = new Node(treeListBean.getId(),-1,treeListBean.getPositionName());
                }else {
                     node = new Node(treeListBean.getId(),treeListBean.getParentId(),treeListBean.getPositionName());
                }
                mDatas.add(node);
            }
        }
        if(mAdapter != null){
            // 展开层级，暂定
            mAdapter.addDataAll(mDatas,0);
        }

        // 默认选择最顶层
        nav_left.setText(originalData.get(0).getPositionName());

        // 加载设备列表

        String positionId = originalData.get(0).getId();
        HashMap map = new HashMap();
        map.put("positionId",positionId);
        currentSelPositionId = positionId;
        requestDevicesListData(map);

        // 假数据
//        for (int i=0;i<10;i++){
//            DeviceBean deviceBean = new DeviceBean();
//            deviceBean.setDeviceName("测试一下"+i);
//            deviceBean.setPositionName("南天门");
//            if(i<4){
//                deviceBean.setStatus(1);
//            }else if(i==6 || i==7){
//                deviceBean.setStatus(2);
//            }else if( i==8 || i == 9){
//                deviceBean.setStatus(3);
//            }else {
//                deviceBean.setStatus(4);
//            }
//            deviceList.add(deviceBean);
//        }

        mILoadingView.hideLoading();
        if(deviceList.size()>0){
            mIEmptyView.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
        }else {
            mIEmptyView.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
        }
        equipListAdapter.setGridViewBeanList(deviceList);
        equipListAdapter.notifyDataSetChanged();
    }

    private void initData() {

//        String aa = "[{\"id\":\"1\",\"positionName\":\"社区网络音频系统\",\"parentId\":\"\",\"addr\":null},{\"id\":\"1a5aec754036453cb915776aef82dbf2\",\"positionName\":\"双塘街道\",\"parentId\":\"1\",\"addr\":null}]";
//        List<TreeListBean> treeListBeanList = new Gson().fromJson(aa,new TypeToken<List<TreeListBean>>() {}.getType());
//        initTreeDatas(treeListBeanList);

        NetWorkManager.getInstance().getNetWorkApiService().getTree().compose(HomeListActivity.this.<BasicResponse<List<TreeListBean>>>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<BasicResponse<List<TreeListBean>>>() {
                    @Override
                    protected void onSuccess(BasicResponse<List<TreeListBean>> response) {
                        if (response != null) {
                            List<TreeListBean> treeListBeanList = response.getData();
                            initTreeDatas(treeListBeanList);
                        }
                    }

                    @Override
                    protected void onFail(BasicResponse<List<TreeListBean>> response) {
                        super.onFail(response);
                        mRefreshLayout.finishRefresh();
                        mILoadingView.hideLoading();
                        mIEmptyView.setVisibility(View.VISIBLE);
                        listView.setVisibility(View.GONE);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        super.onError(e);
                        mRefreshLayout.finishRefresh();
                        mILoadingView.hideLoading();
                        mIEmptyView.setVisibility(View.VISIBLE);
                        listView.setVisibility(View.GONE);
                    }
                });
    }

    /**
     * 底部的控制view显示隐藏
     * */
    private void setBottomControllView() {
        isManager = !isManager;
        equipListAdapter.setCheckOnOff(isManager);

        int visibility = isManager ? View.VISIBLE : View.GONE;
        control_rl.setVisibility(visibility);
    }

    // 操作点击
    @Override
    public void treeOperationClick(View view,int position) {
        if(mBubbleDialog == null) {
            mBubbleDialog =  new CustomOperateDialog(this);
        }
        mBubbleDialog.setClickedView(view);
        mBubbleDialog.show();


        Node node = mDatas.get(position);
        mBubbleDialog.setClickListener(new CustomOperateDialog.OnClickCustomButtonListener() {
            @Override
            public void onOperationItemClick(String str, int index) {
                String id = (String) node.getId();
                Log.e("1111","id====="+id);
                switch (index){
                    case 0:
                        // 删除
                        CVIPaperDialogUtils.showCustomDialog(HomeListActivity.this, "确定要删除该位置吗?", null, "删除", false, new CVIPaperDialogUtils.ConfirmDialogListener() {
                            @Override
                            public void onClickButton(boolean clickConfirm, boolean clickCancel) {
                                if (clickConfirm) {
                                    HashMap map = new HashMap();
                                    map.put("id",id);

                                    NetWorkManager.getInstance().getNetWorkApiService().positionDel(map).compose(HomeListActivity.this.<BasicResponse<String>>bindToLifecycle())
                                            .subscribeOn(Schedulers.io())
                                            .observeOn(AndroidSchedulers.mainThread())
                                            .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                                @Override
                                                protected void onSuccess(BasicResponse<String> response) {
                                                    if (response != null) {
                                                        refreshPositionTreeData();
                                                        if(mBubbleDialog != null && mBubbleDialog.isShowing()) {
                                                            mBubbleDialog.dismiss();
                                                        }
                                                        ToastUtil.makeText(HomeListActivity.this,"删除成功!");
                                                    }
                                                }
                                                @Override
                                                protected void onFail(BasicResponse<String> response) {
                                                    super.onFail(response);

                                                }
                                                @Override
                                                public void onError(@NonNull Throwable e) {
                                                    super.onError(e);
                                                }
                                            });

                                }
                            }
                        });
                        break;
                    case 1:
                        // 编辑
                        CVIPaperDialogUtils.showInputDialog(HomeListActivity.this, "请输入修改后的位置名称", "确定","10字以内", InputType.TYPE_CLASS_TEXT, false, new CVIPaperDialogUtils.inputConfirmDialogListener() {
                            @Override
                            public void onClickButton(boolean clickConfirm, boolean clickCancel, String inputStr) {
                                if(clickConfirm){
                                   if(StringUtils.isEmpty(inputStr)){
                                       ToastUtil.makeText(HomeListActivity.this,"请输入名称!");
                                   }else {
                                       HashMap map = new HashMap();
                                       map.put("id",id);
                                       map.put("positionName",inputStr);

                                       NetWorkManager.getInstance().getNetWorkApiService().positionMod(map).compose(HomeListActivity.this.<BasicResponse<String>>bindToLifecycle())
                                               .subscribeOn(Schedulers.io())
                                               .observeOn(AndroidSchedulers.mainThread())
                                               .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                                   @Override
                                                   protected void onSuccess(BasicResponse<String> response) {
                                                       if (response != null) {
                                                           refreshPositionTreeData();
                                                           if(mBubbleDialog != null && mBubbleDialog.isShowing()) {
                                                               mBubbleDialog.dismiss();
                                                           }
                                                           ToastUtil.makeText(HomeListActivity.this,"修改成功!");
                                                       }
                                                   }
                                                   @Override
                                                   protected void onFail(BasicResponse<String> response) {
                                                       super.onFail(response);

                                                   }
                                                   @Override
                                                   public void onError(@NonNull Throwable e) {
                                                       super.onError(e);
                                                   }
                                               });
                                   }
                                }
                            }
                        });
                        break;
                    case 2:
                        // 添加
                        CVIPaperDialogUtils.showInputDialog(HomeListActivity.this, "请输入要添加的子位置名称", "确定","10字以内",InputType.TYPE_CLASS_TEXT, false, new CVIPaperDialogUtils.inputConfirmDialogListener() {
                            @Override
                            public void onClickButton(boolean clickConfirm, boolean clickCancel, String inputStr) {
                                if(clickConfirm){
                                    if(StringUtils.isEmpty(inputStr)){
                                        ToastUtil.makeText(HomeListActivity.this,"请输入名称!");
                                    }else {
                                        HashMap map = new HashMap();
                                        map.put("parentId",id);
                                        map.put("positionName",inputStr);

                                        NetWorkManager.getInstance().getNetWorkApiService().positionAdd(map).compose(HomeListActivity.this.<BasicResponse<String>>bindToLifecycle())
                                                .subscribeOn(Schedulers.io())
                                                .observeOn(AndroidSchedulers.mainThread())
                                                .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                                    @Override
                                                    protected void onSuccess(BasicResponse<String> response) {
                                                        if (response != null) {
                                                            refreshPositionTreeData();
                                                            if(mBubbleDialog != null && mBubbleDialog.isShowing()) {
                                                                mBubbleDialog.dismiss();
                                                            }
                                                            ToastUtil.makeText(HomeListActivity.this,"添加成功!");
                                                        }
                                                    }
                                                    @Override
                                                    protected void onFail(BasicResponse<String> response) {
                                                        super.onFail(response);

                                                    }
                                                    @Override
                                                    public void onError(@NonNull Throwable e) {
                                                        super.onError(e);
                                                    }
                                                });
                                    }
                                }
                            }
                        });

                        break;
                }
            }
        });
    }


    /**
     * 处理空白页面和listView显示关系
     * */
    protected void judgeEmptyViewShow() {
        if(deviceList.size()>0){
            mIEmptyView.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
        }else {
            mIEmptyView.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
        }
    }

    // 树状item点击
    @Override
    public void onItemClicked(Node node, int position) {
        Log.e("onItemClicked","position======="+position);
//        if (mPop != null && mPop.isShowing()) {
//            mPop.dismiss();
//            mPop = null;
//            nav_left.setSelected(false);
//            nav_left.setCompoundDrawables(null, null, drawable_normal, null);
//        }
        nav_left.setText(node.getName());

        // 加载设备列表
        String positionId = (String) node.getId();
        currentSelPositionId = positionId;
        HashMap map = new HashMap();
        map.put("positionId",positionId);

        NetWorkManager.getInstance().getNetWorkApiService().getDevList(map).compose(HomeListActivity.this.<BasicResponse<List<DeviceBean>>>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<BasicResponse<List<DeviceBean>>>() {
                    @Override
                    protected void onSuccess(BasicResponse<List<DeviceBean>> response) {
                        mILoadingView.hideLoading();
                        if (response != null) {
                            deviceList = response.getData();
                            equipListAdapter.setGridViewBeanList(deviceList);
                            equipListAdapter.notifyDataSetChanged();
                            judgeEmptyViewShow();
                        }
                    }

                    @Override
                    protected void onFail(BasicResponse<List<DeviceBean>> response) {
                        super.onFail(response);
                        mILoadingView.hideLoading();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        super.onError(e);
                        mILoadingView.hideLoading();
                    }
                });
    }

    /**
     * 二维码扫描结果
     * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //处理扫描结果
        if(requestCode==REQUEST_CODE){
            if(null !=data){
                Bundle bundle = data.getExtras();
                if(bundle == null){
                    return;
                }
                if(bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS){
                    String result = bundle.getString(CodeUtils.RESULT_STRING);

                    try {
                        Gson gson = new Gson();
                        ScanDevBean scanDevBean = gson.fromJson(result,ScanDevBean.class);
                        ToastUtil.makeText(HomeListActivity.this,"当前类型=="+scanDevBean.getType()+" \n当前Mac地址=="+scanDevBean.getMac());
                    }catch (JsonSyntaxException e){
                        ToastUtil.makeText(HomeListActivity.this,"二维码类型不支持!");
                    }

                }else if(bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED){
                    ToastUtil.makeText(HomeListActivity.this,"解析二维码失败!");
                }
            }
        }
    }


    @Override
    public void onBackPressed() {
        if (mPop != null && mPop.isShowing()) {
            mPop.dismiss();
            mPop = null;
            nav_left.setSelected(false);
            nav_left.setCompoundDrawables(null, null, drawable_normal, null);
        }else {
            long cTime = new Date().getTime();
            if (first_time == 0 || cTime - first_time > time) {
                first_time = cTime;
                Toast.makeText(getApplicationContext(), "再按一次程序退出", Toast.LENGTH_SHORT).show();
            } else {
                super.onBackPressed();
            }
        }
    }

    // 配合显示上面按钮nav_left 的选中状态
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mPop != null && mPop.isShowing()) {
            mPop.dismiss();
            mPop = null;
            nav_left.setSelected(false);
            nav_left.setCompoundDrawables(null, null, drawable_normal, null);
        }
        return super.onTouchEvent(event);
    }

    // 树状刷新
    private void refreshPositionTreeData() {

        mDatas.clear();
        initData();
    }


    public void showPopupWindow(View parent){//显示下拉弹出的窗口
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        // 显示的宽度为:屏幕的宽度的一半
        View view = LayoutInflater.from(this).inflate(R.layout.popup_window, null);
        if(mPop==null){//注意，布局文件的控件设置为fill_parent，否则此处初始化的窗口大小不会变化
//            mPop = new PopupWindow(getLayoutInflater().inflate(R.layout.popup_window, null),
//                    xpos, 100);//实例化一个popupwindow对象
            mPop = new PopupWindow();
            mPop.setContentView(view);
            mPop.setWidth((int)(windowManager.getDefaultDisplay().getWidth()*0.7));
            mPop.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        }
        // 收起列表
        TextView collapseTxt =  view.findViewById(R.id.collapse);
        collapseTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPop != null && mPop.isShowing()) {
                    mPop.dismiss();
                    mPop = null;
                    nav_left.setSelected(false);
                    nav_left.setCompoundDrawables(null, null, drawable_normal, null);
                }
            }
        });

        /**
         * 这种方法可以处理popupwindows dimiss的时候一些其他的操作，比如让其他控件的隐藏，消失等）:
         * 代码如下popupWindow.setFocusable(false);//focusable要为false(不设置默认的就是False)；
         * //这是Activity 的OnTouchEvent。
         * */
        // 聚焦
        mPop.setFocusable(false);
        // 设置允许在外点击消失
        mPop.setOutsideTouchable(false);
        //这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        mPop.setBackgroundDrawable(new BitmapDrawable());
        mPop.setAnimationStyle(R.style.popupwindow_animation_style);//设置动画
//        mPop.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        mPop.showAsDropDown(parent,0,0);


        RecyclerView mTree = (RecyclerView) view.findViewById(R.id.recyclerview);
        mTree.addItemDecoration(new DividerItemDecoration(HomeListActivity.this, DividerItemDecoration.VERTICAL_LIST));
        mTree.setLayoutManager(new LinearLayoutManager(this));


        //第一个参数  RecyclerView 第二个参数  上下文 /第三个参数
        // 数据集 /第四个参数  默认展开层级数 0为不展开 第五个参数  展开的图标
        //第六个参数  闭合的图标
        mAdapter = new MTreeRecycleAdapter(mTree, HomeListActivity.this,mDatas, 1,R.mipmap.tree_ec,R.mipmap.tree_ex);
        mAdapter.setTreeOperationClickListener(HomeListActivity.this);
        mAdapter.setOnItemClickListener(HomeListActivity.this);
        mTree.setAdapter(mAdapter);
    }


    /**
     * 检查读写权限权限
     */
    @AfterPermissionGranted(Constant.WRITE_PERMISSION_CODE1)
    private void checkWritePermission1() {
        if (!PermissionManager.checkPermission(this, Constant.PERMS_WRITE)) {
            PermissionManager.requestPermission(this, Constant.WRITE_PERMISSION_TIP, Constant.WRITE_PERMISSION_CODE1, Constant.PERMS_WRITE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //将请求结果传递EasyPermission库处理
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 请求权限成功
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

        Toast.makeText(HomeListActivity.this, "授权成功", Toast.LENGTH_LONG).show();
    }


    /**
     * 请求权限失败
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Toast.makeText(HomeListActivity.this, "用户授权失败", Toast.LENGTH_LONG).show();
        /**
         * 若是在权限弹窗中，用户勾选了'NEVER ASK AGAIN.'或者'不在提示'，且拒绝权限。
         * 这时候，需要跳转到设置界面去，让用户手动开启。
         */
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }
}
